package cc.ufinity.networkdiagnose.widget;

import java.text.DecimalFormat;
import java.util.List;
import java.util.Map;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.NetworkManager;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.Task.PingTask;
import cc.ufinity.networkdiagnose.util.StringUtils;
import cc.ufinity.networkdiagnose.util.StringUtils.PING_RESULT;
import cc.ufinity.networkdiagnose.view.R;

public class PingWidgetProxy extends GeneralTestWidget {

    private Activity ctx;
    private Handler handlerChild;
    private Handler handler;
    private Button backBtn;
    private NetworkManager nm;
    private Task task;
    private PingTask pingTask;
    private int taskSize;
    private boolean taskProcessing;
    private int currentTaskNum;

    public static int testFlag = 0;
    public static int taskFlag = 0;   
	
	private boolean isFirst = true;
	
    public PingWidgetProxy(Activity context, Handler handl) {
        super(context);
        inflate(context, R.layout.ping_proxy, this);
        this.ctx = context;
        this.handlerChild = handl;
        backBtn = (Button) this.findViewById(R.id.ping_test_proxy_btnback);
        handler = new Handler() {
            public void handleMessage(Message msg) {
                switch (msg.what) {
                case MessageWhat.PING_SUCCESS:
                    update();
                    //mSendBroadcast(ctx);
                    handlerSendToTarget(handlerChild, MessageWhat.HANDLER_PING);
                    break;
                case MessageWhat.PING_FAILED:
                  //  showMessage(ctx, "PING测试失败，请返回重试！");
                    dismissProgressDialog();
                    //mSendBroadcast(ctx);
                    handlerSendToTarget(handlerChild, MessageWhat.HANDLER_PING);
                    break;
                case MessageWhat.DO_NEXT_TEST:
                    //showTaskResult();
                    break;
                }
            }
        };
        backBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                backToTask(ctx);
            }
        });
        nm = new NetworkManager();
        nm.setHandler(handler);
        startPing();
    }
 
    public void update() {
        this.setDialogProgress(currentTaskNum); 
      //----------------------------------------------------------
		if(isFirst) {
			isFirst = false;
			StringBuffer temp = new StringBuffer();
			GlobalApp.result_PING_test = temp;
		}
		GlobalApp.result_PING_test.append( StringUtils.pingResultToCh(nm.getPingResult()) );
//		System.out.println("PING测试结果：\n" + nm.getPingResult());
	//---------------------------------------------------------- 
        Map<String, String> res = StringUtils.pingResult(nm.getPingResult());
        pingTask.bytes = res.get(PING_RESULT.PING_RESULT_BYTE_NO);
        pingTask.time = res.get(PING_RESULT.PING_RESULT_TIME);
        pingTask.ttl = res.get(PING_RESULT.PING_RESULT_TTL);
        pingTask.count = res.get(PING_RESULT.PING_PACKETS_TRANSMITTED);
        pingTask.successCount = res.get(PING_RESULT.PING_RECEIVED);
        
        
        task.pingTasks.set(currentTaskNum - 1, pingTask);
        taskProcessing = false;
        DecimalFormat df = new DecimalFormat("#0.000");
        task.pingCount = task.testCount + "";
        task.pingSuccessCount = pingTask.successCount;
        task.pingAvgDelay = df.format((float) StringUtils.parseFloat(pingTask.time) / 1000);
        
System.out.println("task.pingCount => " + task.pingCount);
System.out.println("task.pingSuccessCount => " + task.pingSuccessCount);
System.out.println("task.pingAvgDelay => " + task.pingAvgDelay);
        
        if (currentTaskNum == taskSize) {
            ctx.getIntent().putExtra(TAG_REFER_TASK, task);
      //      dismissProgressDialog(); 
        }
    }

    public void startPing() {
        currentTaskNum = 0;
        taskProcessing = false;
        task = (Task) ctx.getIntent().getSerializableExtra(TAG_REFER_TASK);
        final List<PingTask> tasks = task.pingTasks;
        taskSize = tasks.size();
   //    this.showProgressDialog(ctx, "正在进行Ping测试...", taskSize);
        new Thread() {
            public void run() {
                while (currentTaskNum < taskSize) {
                    if (!taskProcessing) {
                        pingTask = tasks.get(currentTaskNum);
                        currentTaskNum++;
                        taskProcessing = true;
                        nm.ping(pingTask.address, task.testCount, 64);
                    }
                }
            }
        }.start();
    } 
}
